package com.zoo.springbootinit.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zoo.springbootinit.model.entity.Post;
import com.zoo.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.boot.CommandLineRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//取消注释运行项目会自动执行
//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {
    @Resource
    private PostService postService;

    @Override
    public void run(String... args) throws Exception {

            String json = "{\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"reviewStatus\":1,\"current\":1}";
            String url = "https://www.code-nav.cn/api/post/list/page/vo";
            String result = HttpRequest
                    .post(url)
                    .body(json)
                    .execute()
                    .body();

            Map<String, Object> map = JSONUtil.toBean(result, Map.class);
            System.out.println(map);
            JSONObject data = (JSONObject) map.get("data");
            System.out.println(data);
            JSONArray records = (JSONArray) data.get("records");
            List<Post> postList = new ArrayList<>();
            for (Object record : records) {
                JSONObject tempRecord = (JSONObject) record;
                Post post = new Post();
                post.setTitle(tempRecord.getStr("title"));
                post.setContent(tempRecord.getStr("content"));
                post.setTags(tempRecord.getStr("tags"));
                post.setUserId(1L);
                postList.add(post);
            }
            boolean b = postService.saveBatch(postList);
            if (b) {
                log.info("获取文章列表并保存到数据库，结果：{}", postList.size());
            } else {
                log.error("获取文章列表并保存到数据库失败");
            }
        }
    }

